package com.cloud.gatewaySpringSecurity.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhozixiong
 * @date 2022/09/06
 */
public class SaveMessage {

    private SaveMessage() {
    }

    public static Mono<Void> save(ServerWebExchange exchange, HttpStatus code, Map<String, Object> map) {
        return save(exchange.getResponse(), code, map);
    }

    public static Mono<Void> save(ServerWebExchange exchange, HttpStatus code, String message) {
        return save(exchange.getResponse(), code, message);
    }

    public static Mono<Void> save(ServerHttpResponse response, HttpStatus code, Map<String, Object> map) {
        //设置状态码
        response.setStatusCode(code);
        //设置返回信息格式
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
        //封装返回信息
        map.put("code", code);
        //转化信息格式
        String body = JSONObject.toJSONString(map);
        DataBuffer buffer = null;
        try {
            buffer = response.bufferFactory().wrap(body.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(buffer));
    }

    public static Mono<Void> save(ServerHttpResponse response, HttpStatus code, String message) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("message", message);
        return save(response, code, map);
    }
}
